import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: 'http://203.57.5.167:8000/',
  // url = base url + request url
  timeout: 10000,
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer' + ' ' + getToken();
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    // console.log(res);
    if (res.code == -1) {
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })
    }
    if (res.code !== 0) {
      if (res.code == -1) {
        this.$router.push({ name: '/login' });
      }
      if (res.text == '顶级节点') {
        return res;
      }
      if (res.isApp == true) {
        return res;
      }
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      };
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log(error);
    // console.log('err11' + error) // for debug
    // timeout of 20000ms exceeded
    if (error.message == 'timeout of 10000ms exceeded') {
      Message({
        message: '请求超时',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
